<template>
  <div class="page-container">
    <h2>数据详情: {{ $route.query.experimentId || 'sample_1' }}</h2>
    <a-divider
      type="horizontal"
      :style="{ borderColor: '#19a7ff', borderWidth: '2px' }"
    />
    <a-row :gutter="24">
      <a-col
        :xs="24"
        :sm="24"
        :md="14"
        :lg="14"
        :xl="14"
        class="details-container"
      >
      <a-descriptions
        :column="1"
        bordered
        :size="descriptionSize"
        :labelStyle="dataLabelStyle"
        class="details-table"
      >
        <a-descriptions-item label="实验数据集">{{this.$route.query.experimentSetId}}</a-descriptions-item>
        <a-descriptions-item label="实验批次">{{this.$route.query.batchId}}</a-descriptions-item>
        <a-descriptions-item label="实验">{{this.$route.query.experimentId}}</a-descriptions-item>
        <a-descriptions-item label="交易哈希">{{this.$route.query.tx_hash || '未知'}}</a-descriptions-item>
        <a-descriptions-item label="图片宽度">{{metadata.width || '未知'}}</a-descriptions-item>
        <a-descriptions-item label="图片高度">{{metadata.height || '未知'}}</a-descriptions-item>
        <a-descriptions-item label="文件大小">{{metadata.file_size || '未知'}}</a-descriptions-item>
        <a-descriptions-item label="文件类型">{{metadata.mime_type || '未知'}}</a-descriptions-item>
        <a-descriptions-item label="创建时间">{{metadata.created_at || '未知'}}</a-descriptions-item>
        <a-descriptions-item label="备注"></a-descriptions-item>
      </a-descriptions>
      <template v-if="$route.query.tx_hash">
        <h2>区块信息摘要</h2>
        <a-descriptions
          :column="1"
          bordered
          :size="descriptionSize"
          :labelStyle="blockInfoLabelStyle"
          class="details-table"
        >
          <a-descriptions-item label="account（归属账号）">{{this.data.owner}}</a-descriptions-item>
          <a-descriptions-item label="sequence（交易序号）">{{this.data.account}}</a-descriptions-item>
          <a-descriptions-item label="ledger_index（区块高度）">{{this.data.ledgerIndex}}</a-descriptions-item>
          <a-descriptions-item label="hash(哈希值)">{{this.data.hash}}</a-descriptions-item>
          <a-descriptions-item label="上链时间">{{this.data.date}}</a-descriptions-item>
        </a-descriptions>
      </template>
    </a-col>
    <a-col
      :xs="24"
      :sm="24"
      :md="10"
      :lg="10"
      :xl="10"
    >
      <div class="image-container">
        <div class="image-wrapper">
          <a-image
            v-if="imgUrl"
            :src="imgUrl"
            alt="图片预览"
            :preview="false"
            class="detail-image"
            @error="handleImageError"
          />
          <div v-else class="error-message">
            <p>图片加载失败</p>
            <p v-if="imageError" style="color: red; font-size: 12px;">{{ imageError }}</p>
          </div>
        </div>
        <div class="button-container">
          <a-button @click="openModal" type="primary">水印查看</a-button>
        </div>
      </div>
    </a-col>
  </a-row>
 </div>
</template>

<script>
import axiosInstance from "@/axios/axios.js";

export default {
  name: "Detail",
  data() {
    return {
      record: {},
      modalOpen: false,
      modalContent: "",
      imgUrl: "",
      imgUrlFortif: "",
      descriptionSize: 'small',
      data: {},
      metadata: {},
      imageError: null,
      dataLabelStyle: {
        color: "red",
        fontWeight: "bold",
        width: "150px",
        fontSize: "14px"
      },
      blockInfoLabelStyle: {
        color: "red",
        fontWeight: "bold",
        width: "150px",
        fontSize: "14px"
      }
    }
  },
  async created() {
    console.log('Route query:', this.$route.query);
    
    try {
      console.log('Query params:', this.$route.query);
      if (this.$route.query.metadata) {
        this.metadata = JSON.parse(this.$route.query.metadata);
        console.log('Parsed metadata:', this.metadata);
      } else {
        console.warn('No metadata found in query params');
      }
      
      const imgUrl = this.$route.query.imgUrl;
      if (imgUrl) {
        if (imgUrl.startsWith('data:image/') && imgUrl.includes('base64,')) {
          const base64Data = imgUrl.split(',')[1];
          if (base64Data && base64Data.length > 0) {
            this.imgUrl = imgUrl;
          } else {
            this.imageError = 'base64数据内容无效';
          }
        } else {
          this.imageError = '接收到的图片数据格式不正确';
        }
      } else {
        this.imageError = '未提供图片数据';
      }
      
      const imgUrlFortif = this.$route.query.imgUrlFortif;
      if (imgUrlFortif && imgUrlFortif.includes('base64,')) {
        this.imgUrlFortif = imgUrlFortif;
      }
    } catch (error) {
      console.error('Error processing data:', error);
      this.imageError = '处理数据时出错';
    }

    if (!this.$cookies.get('jwt') || !sessionStorage.getItem("isLogin")) {
      this.$message.warning('请先登录');
      this.$router.push('/login');
      return;
    }

    // 使用路由参数中的 tx_hash 进行溯源查询
    const tx_hash = this.$route.query.tx_hash;
    if (tx_hash) {
      try {
        // 构建请求参数
        const params = {
          hash: tx_hash,
          username: this.$cookies.get("username")
        };
        
        // 如果有accessId（从grant进入），添加到参数中
        if (this.$route.query.accessId) {
          params.accessId = this.$route.query.accessId;
        }

        // 构建URL查询字符串
        const queryString = Object.entries(params)
          .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
          .join('&');

        const response = await axiosInstance({
          method: "POST",
          url: `/traceback?${queryString}`,
          headers: {
            Authorization: `Bearer ${this.$cookies.get("jwt")}`
          }
        });

        if (response.data.code === 200) {
          this.data = response.data.data;
        } else {
          this.$message.error(response.data.message || '获取溯源信息失败');
        }
      } catch (error) {
        console.error('Traceback error:', error);
        if (error.response?.status === 401) {
          this.$message.error('无访问权限或登录已过期');
          this.$router.push('/login');
        } else {
          this.$message.error(error.response?.data?.message || '获取溯源信息失败');
        }
      }
    } else {
      this.data = {};
    }
  },
  methods: {
    handleImageError(e) {
      console.error('Image load error:', e);
      this.imageError = '图片加载失败，可能是格式不支持或数据损坏';
    },
    async openModal() {
      if (!this.imgUrl) {
        this.$message.warning('图片路径不能为空');
        return;
      }

      this.modalOpen = true;
      
      const formData = new FormData();
      formData.append("imagePath", this.imgUrl);

      try {
        const response = await axiosInstance({
          method: "POST",
          url: "/getWaterMark",
          headers: {
            'Content-Type': 'multipart/form-data',
            Authorization: `Bearer ${this.$cookies.get("jwt")}`
          },
          data: formData,
        });

        if (response.data.code === 200) {
          this.modalContent = response.data.data;
        } else {
          this.$message.error(response.data.message || '获取水印信息失败');
        }
      } catch (error) {
        console.error('Watermark error:', error);
        if (error.response?.status === 401) {
          this.$message.error('无访问权限或登录已过期');
          this.$router.push('/login');
        } else {
          this.$message.error(error.response?.data?.message || '获取水印信息失败');
        }
      }
    }
  }
}
</script>

<style scoped>
.page-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.details-container {
  padding-right: 20px;
}

.details-table {
  width: 100%;
  margin-bottom: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.details-table :deep(.ant-descriptions-item) {
  padding: 12px 16px;
}

.details-table :deep(.ant-descriptions-item-label) {
  width: 150px;
  color: #ff4d4f;
  font-weight: bold;
  font-size: 14px;
}

.image-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  background-color: #fafafa;
  border-radius: 8px;
  margin-top: 0;
  height: 100%;
}

.image-wrapper {
  width: 100%;
  height: calc(100% - 60px);
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.detail-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  border-radius: 4px;
}

.error-message {
  text-align: center;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.button-container {
  margin-top: auto;
  text-align: center;
  padding: 10px 0;
}

@media (max-width: 768px) {
  .page-container {
    padding: 10px;
  }

  .details-container {
    padding-right: 0;
    margin-bottom: 20px;
  }

  .image-container {
    margin-top: 20px;
  }

  .image-wrapper {
    height: 300px;
  }
}
</style>
